var cart = function () {

    var chooseHandle = function () {
        //商品选择
        $('.proChoose').on('click', function () {
            var i = $(this);
            //获得当前商品所属店铺的总共商品数量
            var thisParent = $(this).parents('.am-container');
            var thisShopProductsCount = thisParent.find('.proChoose').length;
            //根据样式判断
            if (i.hasClass('uncheck-icon')) {
                //本身是未选择,则选中后检查是否都选择,若都选中则要操作店铺了
                i.removeClass('uncheck-icon').addClass('check-icon');
                var thisCheckedProductsCount = thisParent.find('.cart-shop-pro').find('.check-icon').length;
                if (thisCheckedProductsCount == thisShopProductsCount) {
                    thisParent.find('.shopChoose').click();
                }
            } else {
                i.removeClass('check-icon').addClass('uncheck-icon');
                if(thisParent.find('.shopChoose').hasClass('check-icon')){
                    thisParent.find('.shopChoose').removeClass('check-icon').addClass('uncheck-icon');
                }
            }
            getMoney();
        });

        //店铺选择
        $('.shopChoose').on('click', function () {
            var i = $(this);
            var shops = $(".shopChoose");
            var OwnProducts = i.parents(".am-container").find('.proChoose');
            var products = $('.proChoose');
            if(i.hasClass('check-icon')){
                //去掉该店铺下的所有标记过的商品标记
                shops.removeClass('check-icon').addClass('uncheck-icon');
                //所有商店都得去掉
                OwnProducts.removeClass('check-icon').addClass('uncheck-icon');
                i.removeClass('check-icon').addClass('uncheck-icon');
            }else{
                //去掉该店铺下的所有标记过的商品标记
                shops.removeClass('check-icon').addClass('uncheck-icon');
                products.removeClass('check-icon').addClass('uncheck-icon');
                OwnProducts.removeClass('uncheck-icon').addClass('check-icon');
                i.removeClass('uncheck-icon').addClass('check-icon');
            }
            getMoney();
        });

        //全选
        $('.chooseAll').click(function () {
            var shops = $('.shopChoose');
            var products = $('.proChoose');
            var _self = $(this);
            if(_self.hasClass('uncheck-icon')){
                shops.removeClass('uncheck-icon').addClass('check-icon');
                products.removeClass('uncheck-icon').addClass('check-icon');
                _self.removeClass('uncheck-icon').addClass('check-icon');
            }else{
                shops.removeClass('check-icon').addClass('uncheck-icon');
                products.removeClass('check-icon').addClass('uncheck-icon');
                _self.removeClass('check-icon').addClass('uncheck-icon');
            }

        });

        function getMoney() {
            var selects = $('.proChoose.check-icon');
            var total = 0;
            selects.each(function (index) {
                var _para = $(this).parents('.cart-shop-pro');
                var singlePrice = _para.find('.proPrice').html();
                var proNum = _para.find('.proNum').html();
                total += singlePrice * proNum;
            });
            $('i.totalPrice').html(total);
            $('span.totalSort').html(selects.length);
        }


    };

//对购物车的内容进行编辑（增减数量和删除）
    var Edit = function () {
        var shopsIcon = $('.shopChoose');
        var products = $('.proChoose');
        $('.editCart').on('click', function () {
            shopsIcon.removeClass('check-icon').addClass('uncheck-icon');
            products.removeClass('check-icon').addClass('uncheck-icon');
            var tag = $(this).text();
            var confirmBtn = $('#Cart');
            if (tag == "编辑") {
                //编辑的时候，下面的button需要去掉“结算”的类，添加上“删除”的类
                confirmBtn.removeClass('settleCart').addClass('deleteCart');
                confirmBtn.html("删除").parent().prev().html('');
                $('.chooseAllNone').removeClass('am-hide');
                var proNum = $('.editBox').find('i.proNum');
                proNum.each(function (index) {
                    var html = '<div class="num-box am-text-center"><span class="am-inline-block cut-btn">' +
                        '<i class="am-inline-block cut-icon"></i></span>' +
                        '<input type="num" value="' + $(this).text() +
                        '" class="am-form-field am-inline-block am-text-center buyNum xs-font"/>' +
                        '<span class="am-inline-block add-btn"><i class="am-inline-block plus-icon"></i></span></div>';
                    $('.editBox').eq(index).html(html);
                });
                $(this).text("完成");
            } else {
                //完成的时候，下面的button需要去掉“删除”的类，添加上“结算”的类
                confirmBtn.removeClass('deleteCart').addClass('settleCart');
                confirmBtn.html("结算(<span class='totalSort'>0<span>)").parent().prev().html('合计<span class="money-color">￥<i class="totalPrice">0</i></span>');
                $('.chooseAllNone').addClass('am-hide');
                //改变购买数量操作
                var buyNum = $('.buyNum');
                buyNum.each(function (index) {
                    var html = '×<i class="proNum">' + $(this).val() + '</i>';
                    $('.editBox').eq(index).html(html);
                });
                $(this).text("编辑");
            }


            //编辑购物车的时候的加减操作
            $('.editBox').delegate('.cut-btn', 'click', function () {
                var self = $(this).find('.cut-icon');
                if(self.attr("data-loading")){
                    return false;
                }
                //显示loading
                $('#loading').css('visibility','visible');
                autoSize($('#loading'));

                var curObjCartId = self.parents('.cart-shop-pro').attr('data-cartProId');
                var num = Number(self.parents().siblings('.buyNum').val());
                if (num <= 1) {
                    $('#loading').css('visibility','hidden');
                    messageBox("不能再少了");
                } else {
                    self.attr("data-loading","true");
                    $.post('/modCartCount', {cartId: curObjCartId, type: "cut"}).then(function (msg) {
                        self.removeAttr("data-loading");
                        if (msg.code != 200) {
                            //修改数据失败
                            $('#loading').css('visibility','hidden');
                            messageBox("减少数量失败", 'alert');
                            return;
                        }else if(msg.code == 103){
                            messageBox("您还未登录，请登录后操作");
                            $('#loading').css('visibility','hidden');
                            doLogin();
                        } else {
                            $('#loading').css('visibility','hidden');
                            num = num - 1;
                            self.parents().siblings('.buyNum').val(num);
                        }
                    }, function (error, err) {
                        self.removeAttr("data-loading");
                        $('#loading').css('visibility','hidden');
                        console.log(error, err);
                        messageBox("减少数量失败", 'alert');
                    })
                }

            });


            $('.editBox').delegate('.add-btn', 'click', function () {
                var self = $(this).find('.plus-icon');
                if(self.attr("data-loading")){
                    return false;
                }

                $('#loading').css('visibility','visible');
                autoSize($('#loading'));

                var curObjCartId = self.parents('.cart-shop-pro').attr('data-cartProId');
                var num = Number(self.parents().siblings('.buyNum').val());
                self.attr("data-loading","true");
                $.post('/modCartCount', {cartId: curObjCartId, type: "plus"}).then(function (msg) {
                    self.removeAttr("data-loading");
                    if (msg.code != 200) {
                        //修改数据失败
                        messageBox("添加数量失败", 'alert');
                        $('#loading').css('visibility','hidden');
                        return;
                    } else if(msg.code == 103){
                        messageBox("您还未登录，请登录后操作");
                        $('#loading').css('visibility','hidden');
                        doLogin();
                    }else {
                        $('#loading').css('visibility','hidden');
                        num = num + 1;
                        self.parents().siblings('.buyNum').val(num);
                    }
                }, function (error, err) {
                    self.removeAttr("data-loading");
                    $('#loading').css('visibility','hidden');
                    console.log(error, err);
                    messageBox("添加数量失败", 'alert');
                })
            });
        });


    };

//删除操作
    var deleteGood = function () {
        /*删除时需要进行确认*/
        $('.cart-fixed').delegate('.deleteCart', 'click', function () {
            var deleteObject = getSelectedItem();
            if (!deleteObject.length) {
                messageBox("没有选中要删除的商品哦", 'alert');
                return;
            }
            $('#delete').modal({
                relatedTarget: this,
                onConfirm: function (options) {
                    $.post('/delCart', {cartId: JSON.stringify(deleteObject)}).then(function (msg) {
                        if (msg.code == 200) {
                            messageBox('删除成功');
                            var removeObj = $('.proChoose.check-icon');
                            removeObj.each(function () {
                                if ($(this).parent('.cart-shop-pro').siblings('.md-line-height').find('.shopChoose').hasClass('check-icon')) {
                                    $(this).parent('.cart-shop-pro').parents('.am-container').remove();
                                } else {
                                    $(this).parent('.cart-shop-pro').remove();
                                }
                            })
                        }else if(msg.code == 103){
                            messageBox("您还未登录，请登录后操作");
                            doLogin();
                        } else {
                            messageBox(msg.message, 'alert');
                        }
                    })
                },
                onCancel: function () {
                    return false;
                }
            });
        });
    };
    //获得被选中的购物车商品的id的函数
    function getSelectedItem() {
        var items = [];
        var pros = $('.cart-shop-pro').find('.check-icon');
        alert(pros.length);
        if(!pros.length){
            return [];
        }else{
            pros.each(function (item, index, array) {
                items.push($(this).parent('.cart-shop-pro').attr('data-cartProId'));
            });
            return items;
        }
    }

    var goToOrderConfirm = function () {
        $('.cart-fixed').delegate('.settleCart','click', function () {
            var selectShop = $('.shopChoose.check-icon');
            var self = $(this);
            self.attr('disabled', 'disabled');
            if (selectShop.length != 1) {
                messageBox("一次无法提交两个店铺的订单哦");
                self.removeAttr('disabled');
            } else {
                var selectPros = $('.proChoose.check-icon');
                if (selectPros.length > 0) {
                    var checkProduct = [];
                    selectPros.each(function (index, item) {
                        var temp = {};
                        temp.product = $(this).parents('.cart-shop-pro').attr('data-productId');
                        temp.count = parseInt($(this).parents('.cart-shop-pro').find('i.proNum').html());
                        checkProduct.push(temp);
                    });
                    var products = {
                        products: checkProduct
                    };
                    var params = new Base64().encode(JSON.stringify(products));
                    self.removeAttr('disabled');
                    window.location.href = '/confirm?params=' + params;
                } else {
                    messageBox("请先选择商品哦");
                    self.removeAttr('disabled');
                }
            }
        })
    };

    return {
        init: function () {
            chooseHandle();
            Edit();
            deleteGood();
            goToOrderConfirm();
        }
    }
}();
